//
//  NSString+Action.m
//  zhibay
//
//  Created by peter on 15/1/24.
//  Copyright (c) 2015年 union. All rights reserved.
//

#import "NSString+Action.h"
#import <CommonCrypto/CommonDigest.h>
#import "YWGTMBase64.h"
@implementation NSString (Action)

- (NSString*)urlDecode
{
    return [self stringByReplacingPercentEscapesUsingEncoding:
                            NSUTF8StringEncoding];
}

- (NSString *)urlEncode
{
    return [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)base64Decode
{
    return [YWGTMBase64 stringByBase64String:self];
}

- (NSString *)base64Encode
{
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){
       NSData *encodeData = [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
        return [[NSString alloc] initWithData:encodeData encoding:NSUTF8StringEncoding];
    }
    else{
        return [YWGTMBase64 base64StringBystring:self];
    }
}


- (NSString *)md5
{
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    const char *bytes = [self UTF8String];
    CC_MD5(bytes, (CC_LONG)strlen(bytes), result);
    
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3], result[4],
            result[5], result[6], result[7], result[8], result[9],
            result[10], result[11], result[12], result[13], result[14], result[15]];
}

+ (BOOL)isInValidString:(id)object
{
    return object == nil || ![object isKindOfClass:[NSString class]] ||  [object isEqual:[NSNull null]] || [object length] == 0;
}

+ (NSString *)fillContentIfSelfNotValid:(id)object defaultString:(NSString *)string {
    return [NSString isInValidString:object] ? string : object;
}

- (BOOL)isVaildMail
{
    return [[NSPredicate predicateWithFormat:@"self matches %@",@"^[^@]+@[^@]+$"] evaluateWithObject:self];
}

- (BOOL)isVaildTel
{
    return [[NSPredicate predicateWithFormat:@"self matches %@",@"1\\d{10}"] evaluateWithObject:self];
}

- (BOOL)isChinese
{
    return [[NSPredicate predicateWithFormat:@"self matches %@",@"[\u4e00-\u9fa5]+"] evaluateWithObject:self];
}

- (NSString *)replaceBlank
{
    return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
}

- (NSString *)filterNonNumber {
    NSString *stringFliterInValidNumber = [self stringByReplacingOccurrencesOfString:@"\\D" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, self.length)];
    return stringFliterInValidNumber;
    
}
@end
